package com.sinosoft.dsp.platform.components.portal.input.elements;

import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;

import org.hibernate.Query;

import com.sinosoft.builder.templates.concept.TagElementParameterType;
import com.sinosoft.builder.templates.concept.TagElementType;
import com.sinosoft.dsp.platform.exception.SinoPlatformException;
import com.sinosoft.dsp.system.core.log.Log;
import com.sinosoft.dsp.platform.services.CodeSetService;
import com.sinosoft.dsp.platform.utils.SinoManagedBean;
import com.sinosoft.dsp.system.utils.Const;

public class SelectManyTagElememt implements ISinoTagElement {

	private static final Log log = Log.getLog(SelectManyTagElememt.class
			.getName());

	private List<Object> values;

	private List<SelectItem> items;

	public List<Object> getValues() {
		return values;
	}

	public void setValues(List<Object> values) {
		this.values = values;
	}

	public List<SelectItem> getItems() {
		return items;
	}

	public void setItems(List<SelectItem> items) {
		this.items = items;
	}

	@Override
	public boolean isEmpty() {
		if (values == null || values.size() == 0) {
			return true;
		}
		boolean rtn = false;
		for (Object obj : values) {
			if (obj != null) {
				rtn = true;
			}
		}
		return rtn;
	}

	@Override
	public void setParameter(Query query, String key) {
		if (!isEmpty()) {
			// TODO
		}
	}

	@Override
	public void initValue(TagElementType type) throws SinoPlatformException {
		try {
			if (type != null) {
				CodeSetService css = SinoManagedBean.findBean("codeSetService");
				// 初始化item
				if (!Const.isEmpty(type.getCodeSetId())) {
					items = css.getRootSubCodesSelectItems(type.getCodeSetId());
				} else if (type.getTagElementParameter() != null) {
					items = new ArrayList<SelectItem>();
					for (TagElementParameterType tep : type
							.getTagElementParameter()) {
						items.add(new SelectItem(tep.getKey(), tep.getValue()));
					}
				}

				// 初始化value
				String tvs = type.getValue();
				if (!Const.isEmpty(tvs)) {
					values = new ArrayList<Object>();
					String[] vs = tvs.split(",");
					if (!Const.isEmpty(type.getCodeSetId())) {
						for (String v : vs) {
							values.add(css.getCode(type.getCodeSetId(), v));
						}
					} else {
						for (String v : vs) {
							values.add(v);
						}
					}
				}

			}
		} catch (Exception e) {
			log.error("初始化多选框出现错误。");
			throw new SinoPlatformException("初始化多选框出现错误。");
		}
	}
}
